import fs from "fs";
import { CollegeInfo, CollegeType } from "../../models/College-info.js";
import { School } from "../../models/School.mjs";
import { Province } from "../../models/Province.mjs";
import { StatisticsService } from "./statisticsService.mjs";

export class ImportService {
  static async importSchoolData(file) {
    try {
      // 读取上传的文件
      const fileData = fs.readFileSync(file.path, "utf-8");
      const jsonData = JSON.parse(fileData);

      // 清空现有数据
      await School.deleteMany({});

      // 导入新数据
      const schools = await School.insertMany(jsonData);

      // 获取省份数据
      const provinces = await Province.find({});

      // 更新统计数据
      const statistics = await StatisticsService.updateStatistics(
        schools,
        provinces
      );

      // 删除临时文件
      fs.unlinkSync(file.path);

      return statistics;
    } catch (error) {
      throw error;
    }
  }
}

export class importCollegesInfo {
  static async importCollegesInfo(file) {
    try {
      const fileData = fs.readFileSync(file.path, "utf-8");
      const jsonData = JSON.parse(fileData);

      // 清空现有数据
      await CollegeInfo.deleteMany({});

      // 2. 遍历数据，动态处理类型
      const collegesWithTypes = await Promise.all(
        jsonData.map(async (college) => {
          // 检查类型是否存在，不存在则创建
          const typeName = college.type?.trim();
          // if (!typeName) throw new Error(`大学 ${college.name} 的类型为空`);

          const collegeType = await CollegeType.findOneAndUpdate(
            { name: typeName },
            { $setOnInsert: { name: typeName } }, // 不存在时创建
            { upsert: true, new: true }
          );

          // 返回处理后的数据（替换 type 字符串为 ObjectId）
          return {
            ...college,
            type: collegeType._id, // 替换为引用
          };
        })
      );

      // 3. 批量插入大学数据
      const result = await CollegeInfo.insertMany(collegesWithTypes);
      return result;
    } catch (error) {
      throw error;
    }
  }
}
